﻿using System.Xml.Serialization;
using System.IO;
using Ionic.Zip;
namespace HNAlbum.Logic.Entity
{
    /// <summary>
    /// Pikachoose item data type
    /// </summary>
    [XmlRoot("Photo")]
    public class HNAlbumPhoto : EntityBase
    {

        #region Constants
        public const string PHOTO_FOLDER = "Photos";
        public const string SOURCE_FOLDER = "Sources";
        public const string THUMB_FOLDER = "Thumbnails";
        #endregion

        #region Properties
        [XmlElement("Id", Order = 0)]
        public string Id { get; set; }
        [XmlElement("Name", Order = 1)]
        public string Name { get; set; }
        [XmlElement("Caption", Order = 2)]
        public string Caption { get; set; }
        [XmlElement("Src", Order = 3)]
        public string Source { get; set; }
        [XmlIgnoreAttribute]
        public string Url { get; set; }
        /// <summary>
        /// File name in preview folder
        /// </summary>
        [XmlIgnoreAttribute]
        public string PreviewName
        {
            get
            {
                return string.Format("photo{0}.jpg", Id);
            }
        }
        [XmlIgnoreAttribute]
        public string AlbumId { get; set; }
        #endregion

        /// <summary>
        /// Empty constructor for XML serialisation
        /// </summary>
        public HNAlbumPhoto() { }
        /// <summary>
        /// Create a temp source file
        /// </summary>
        /// <returns></returns>
        public string CreateTempSource()
        {
            //First clean the temp folder
            CleanUploadFolder();
            
            //Get the source file
            FileInfo sourceFile = new FileInfo(Path.Combine(AppPhysicalPath, ApplicationFoler.Album, AlbumId, SOURCE_FOLDER, Source));
            //Remove all attributes
            File.SetAttributes(sourceFile.FullName, FileAttributes.Normal);
            //Copy it to temp upload folder
            FileInfo tempFile = sourceFile.CopyTo(Path.Combine(AppPhysicalPath, ApplicationFoler.Upload, Name), true);

            //Create a ZIP archive so user can download the photo
            ZipFile zip = new ZipFile(Path.Combine(AppPhysicalPath, ApplicationFoler.Upload, Name + ".zip"));
            zip.AddFile(tempFile.FullName, string.Empty);
            zip.Save();

            //The return temp file URL
            return string.Format("{0}/{1}", ApplicationFoler.Upload, tempFile.Name);
        }
    }
}
